package com.example.excelimporter.listener;

import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.read.listener.ReadListener;
import com.alibaba.excel.util.ListUtils;
import com.example.excelimporter.model.ErrorRecord;
import com.example.excelimporter.model.ImportResult;
import com.example.excelimporter.model.TemplateConfig;
import com.example.excelimporter.service.*;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

public class ExcelDataListener implements ReadListener<Object> {

    private final TemplateConfig templateConfig;
    private final DataValidationService dataValidationService;
    private final DataMappingService dataMappingService;
    private final DataSaveService dataSaveService;

    private final List<Object> validData = ListUtils.newArrayList();
    private final List<Object> invalidData = ListUtils.newArrayList();

    public ExcelDataListener(TemplateConfig templateConfig,
                           DataValidationService dataValidationService,
                           DataMappingService dataMappingService,
                           DataSaveService dataSaveService) {
        this.templateConfig = templateConfig;
        this.dataValidationService = dataValidationService;
        this.dataMappingService = dataMappingService;
        this.dataSaveService = dataSaveService;
    }

    @Override
    public void invoke(Object data, AnalysisContext context) {
        // 1. 数据校验
        String validationError = dataValidationService.validate(data, templateConfig);
        if (validationError != null) {
            invalidData.add(data);
            dataSaveService.saveInvalidData(data, validationError, templateConfig.getTargetTable());
            return;
        }

        // 2. 数据映射
        Object mappedData = dataMappingService.mapData(data, templateConfig);

        // 3. 数据保存
        dataSaveService.saveValidData(mappedData, templateConfig.getTargetTable());
        validData.add(mappedData);
    }

    @Override
    public void doAfterAllAnalysed(AnalysisContext context) {
        // 所有数据解析完成后执行
    }

    public ImportResult buildImportResult() {
        ImportResult result = new ImportResult();
        result.setTotalCount(validData.size() + invalidData.size());
        result.setSuccessCount(validData.size());
        result.setErrorCount(invalidData.size());
        result.setErrorRecords(Collections.<ErrorRecord>emptyList()); // 需要从dataSaveService获取错误记录
        return result;
    }
}
